import cn.edu.dgut.Entity.User;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@WebServlet("/uploadImage")
public class UploadImageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String,String> infoMap = (Map<String, String>) request.getSession().getAttribute("isLogin");
        String user_number = infoMap.get("user_number");
        //根据工号查找用户
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> list = null;
        String head_img = null;
        try {
            list = upload.parseRequest(request);
            for (FileItem fi : list ) {
                //判断是否是文本域
                if(!fi.isFormField()){
                    if(fi.getSize()!=0){ //判断文件上传框是否选择了图片
                        head_img = fi.getName();
                        String path = getServletContext().getRealPath("/uploadImages");
                        InputStream is = fi.getInputStream();
                        FileOutputStream os = new FileOutputStream(new File(path, head_img));
                        IOUtils.copy(is,os);
                        os.close();
                        is.close();
                        fi.delete();
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        if(head_img==null){
            head_img="boy.png";
        }
        /*user.setHead_img(head_img);
        new ReadFile().resetUserInfo(user);//写入文件中*/

        EntityManager em = (EntityManager) request.getAttribute("_entity.manager");
        String jpql = "select u from User u where u.user_number = :number1";
        Query query = em.createQuery(jpql);
        query.setParameter("number1",user_number);
        User user = (User)query.getSingleResult();
        user.setHead_img(head_img);
        em.persist(user);

        response.sendRedirect("/info.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
